using System;
using System.Threading;

public static class Program {
   public static void Main() {
      // Construct an AutoResetEvent (initially not signalled)
      AutoResetEvent are = new AutoResetEvent(false);

      // Tell the thread pool to wait on the AutoResetEvent
      RegisteredWaitHandle rwh = ThreadPool.RegisterWaitForSingleObject(
         are,             // Wait on this AutoResetEvent
         EventOperation,  // Callback this method
         null,            // Pass null to EventOperation
         5000,            // Wait 5 seconds for the event to become signalled
         false);          // Call EventOperation everytime the event is signalled

      // Start our loop
      Char operation; 
      do {
         Console.WriteLine("S=Signal, Q=Quit?");
         operation = Char.ToUpper(Console.ReadKey(true).KeyChar);
         if (operation == 'S') {
            // User want to signal the event, set it
            are.Set();
         }
      } while (operation != 'Q');

      // Tell the thread pool to stop waiting on the event
      rwh.Unregister(null);
   }

   // This method is called whenever the event is signalled or
   // when 5 seconds have elapsed since the last signalling/timeout
   private static void EventOperation(Object state, Boolean timedOut) {
      if (timedOut) {
         Console.WriteLine("Timed-out while waiting for the AutoResetEvent.");
      } else {
         Console.WriteLine("The AutoResetEvent became signalled.");
      }
   }
}
